<?php
namespace app\api\controller;
use app\model\VipRecord as VipRecordModel;
use app\model\Token as TokenModel;
use think\Db;

use app\common\wechat\Pay;


class VipRecord extends Base
{   
    protected $noCheckToken = ['wxPayCallback'];

    /**
     * @Author   CCH
     * @DateTime 2020-05-23T12:10:10+0800
     * @return   数据列表
     */
    public function index(){
        $user_id = $this->login_user['user_id'];
        $map_params = [
            ['key'=>'status','type'=>'='],
        ];
        $map = getSearchParam($map_params);
        $map[] = ['user_id','=',$user_id];
        $map[] = ['status','=',1]; // 目前只显示已支付记录

        $model = new VipRecordModel();
        $page_param = ['page'=>input('page_index',1),'list_rows'=>input('page_size',10)];
        $list = $model->where($map)->order('id desc')->paginate($page_param)->toarray();
        foreach ($list['data'] as $k => $vo) {
        }
        return apiResult('2000','获取成功',$list);
    }

    /**
     * 获取详情
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function read($id){
        $user_id = $this->login_user['user_id'];
        $model = new VipRecordModel();
        $data = $model->where('id',$id)->find();
        if (!empty($data)) {
        }
        
        return apiResult('2000','获取成功',$data);
    }




    /**
     * 点赞
     * @Author   cch
     * @DateTime 2020-05-26T17:22:45+0800
     * @return   [type]                   [description]
     */
    public function save(){
        $user_id = $this->login_user['user_id'];

        $param = file_get_contents('php://input');
        $param = json_decode($param,true);
        $fields = [
            'must'=>['vip_rules_id'],
            'nomust'=>[]
        ];
        $params = paramFilter($param,$fields);
        if (!empty($params['error_msg'])) {
            return apiResult('5000',$params['error_msg']);
        }
        

        $data = Db::name('vip_rules')->where('id',$params['vip_rules_id'])->find();
        // if ($data['status'] != 1) {
        //     return apiResult('5000','商品已下架');
        // }
        
        $save_data = [
            'user_id'=>$user_id,
            'order_sn'=>uuidCreate(),
            'name'=>$data['name'],
            'vip_rules_id'=>$params['vip_rules_id'],
            'days'=>$data['days'],
            'price'=>$data['price'],
            'ctime'=>time()
        ];

        $model = new VipRecordModel();
        if ( !$id = $model->insertGetId($save_data) ) {
            return apiResult('5000','下单失败，请重试');
        }

        return apiResult('2000','下单成功',$id);
    }

    /**
     * 小程序支付
     * @Author   cch
     * @DateTime 2020-05-26T17:22:00+0800
     * @param    $save_data 保存的数据
     * @return   提交结果
     */
    public function wxPay($id){
        $model = new VipRecordModel();
        $order = $model->where('id',$id)->find();
        if (empty($order) || $order['status'] != 0) {
            return apiResult('5000','该订单无法支付');
        }
        $uinfo = Db::name('user')->where('id',$order['user_id'])->find();
        $openid = $uinfo['openid'];

        if (empty($openid)) {
            return apiResult('5000','openid为空');
        }

        $price = $order['price'];
        // $price = 0.01;

        $config = config('config.wxpay');
        $appId = $config['appid'];
        $mchId = $config['mchid'];
        $payKey = $config['paykey'];
        // $notify_url = request()->domain().'/index.php/index/order/wxPayCallback';
        $notify_url = url('wxPayCallback',[],'',true);

        $pay = new Pay($appId, $mchId, $payKey);
        $result = $pay->order($order['order_sn'],$price,$openid,'VIP购买'.$order['name'],'',2,$notify_url);
        if ($result['status'] == 1) {
            return apiResult('2000','提交成功',$result['data']);
        }else{
            return apiResult('5000',$result['msg']);
        }
    }

    public function wxPayCallback(){
        $xml = file_get_contents('php://input');
        Db::name('test')->insert([
            'content'=>$xml
        ]);
        $params = xmlToArray($xml);
        
        if($params['result_code']=='SUCCESS' && $params['return_code']=="SUCCESS"){
            $order_sn = $params['out_trade_no'];
            $data = Db::name('vip_record')->where('order_sn',$order_sn)->find();

            if ($data['status'] != 0) {
                exit();
            }
            
            $save_data = ['status'=>1,'trade_no'=>$params['transaction_id'],'pay_time'=>time()];
            if ( Db::name('vip_record')->where('id',$data['id'])->update($save_data) !== false ) {

                $uinfo = Db::name('user')->where('id',$data['user_id'])->find();
                $user_data = [];
                if ($uinfo['vip_time'] >= date('Y-m-d')) {
                    $vip_time = strtotime($uinfo['vip_time']) + (3600 * 24 * $data['days']);
                    $user_data['vip_time'] = date('Y-m-d',$vip_time);
                }else{
                    $vip_time = time() + (3600 * 24 * $data['days']);
                    $user_data['vip_time'] = date('Y-m-d',$vip_time);
                }
                Db::name('user')->where('id',$data['user_id'])->update($user_data);

                // // 发送小程序通知
                // $openid = Db::name('user')->where('id',$data['user_id'])->value('openid');
                // $notify_data = [
                //     "name1" => [
                //         "value"=> Db::name('vip_rule')->where('id',$data['vip_rule_id'])->value('name')
                //     ],
                //     "date2" => [
                //         "value"=> date('Y年m月d日')
                //     ],
                //     "thing3" => [
                //         "value"=> $data['days'].'天'
                //     ],
                //     "thing4" => [
                //         "value"=> '可享受多项会员优惠'
                //     ]
                // ];
                // $notify_status = \app\common\wechat\Util::sendUniformMessage($openid,'9kEY6F_TcoHhkpacKYOIr5ry25xPhtT2xz3dcczFe7U',$notify_data,'/pages/mine/mine');
            }
            return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        }
        return '';
    }
  



}
